package org.apache.rocketmq.proxy.grpc;

import io.grpc.Server;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.common.utils.StartAndShutdown;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;


/**
 * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
 * @author：陈清风扬，个人微信号：chenqingfengyangjj。
 * @date:2025/1/3
 * @方法描述：Grpc服务器
 */
public class GrpcServer implements StartAndShutdown {
    private static final Logger log = LoggerFactory.getLogger(LoggerName.PROXY_LOGGER_NAME);

    //Grpc服务器本身
    private final Server server;

    //服务器关闭的超时时间
    private final long timeout;

    //服务器关闭的时间单位
    private final TimeUnit unit;

    protected GrpcServer(Server server, long timeout, TimeUnit unit) {
        this.server = server;
        this.timeout = timeout;
        this.unit = unit;
    }

    //启动服务器的方法
    public void start() throws Exception {
        this.server.start();
        log.info("grpc server start successfully.port："+ server.getPort());
    }

    //关闭服务器的方法
    public void shutdown() {
        try {//等待服务器完全关闭，timeout就是等待的超时时间
            this.server.shutdown().awaitTermination(timeout, unit);
            log.info("grpc server shutdown successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}